//====utils.es6====//

const arrayProto = Array.prototype
	, slice = arrayProto.slice
	, obj = Object
	, objProto = Object.prototype
	, toString = objProto.toString
	, assign = obj.assign
	, strProto = String.prototype
	, upper = strProto.toUpperCase
	;

const reExt = /\.([a-z0-9-_]+)$/i
	, reTrim = /^[\s\t\r\n]+|[\s\t\r\n]+$/g
	;

function isString(obj) {
	return toString.call(obj) === '[object String]';
}

function trim(value) {
	return isString(value) ? value.replace(reTrim, '') : '';
}

function isArray(obj) {
	return toString.call(obj) === '[object Array]';
}

function isObject(obj) {
	return toString.call(obj) === '[object Object]';
}

function isUndefined(obj) {
	return typeof obj === 'undefined';
}

function undefinedOr(obj, then) {
	return typeof obj === 'undefined' ? then : obj;
}

function isset(obj) {
	return typeof obj === 'undefined' || obj === null;
}

function unsetOr(obj, then) {
	return typeof obj === 'undefined' || obj === null ? then : obj;
}

function emptyStrOr(value, then) {
	let trimValue = trim(value);
	return trimValue === '' ? then : value;
}

function jsonDecode(value, then) {
	var data;
	try {
		data = JSON.parse(value);
	}
	catch (error) {
		data = then;
		console.error('jsonDecode error', value, error);
	}
	return data;
}

function jsonEncode(value) {
	return JSON.stringify(value);
}

function diffDate(date) {
	var newDate = new Date();
	return newDate.valueOf() - date.valueOf();
}

function callFunc(bind, fn) {
	var args = [];
	if (typeof bind === 'function') {
		args = slice.call(arguments, 1);
		fn = bind;
		bind = null;
	}
	else {
		bind = bind || null;
		if (typeof fn !== 'function')
			return false;
		args = slice.call(arguments, 2);
	}
	fn.apply(bind, args);
	return true;
}

function round(value, precision) {
	if (isNaN(value))
		value = 0.00;
	if (typeof precision === 'undefined' || isNaN(precision))
		precision = 0;
	precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
	return Math.round(value * precision) / precision;
}

const KB = 1024
	, MB = 1024 * 1024
	, GB = 1024 * 1024 * 1024
	, TB = 1024 * 1024 * 1024 * 1024;

function adjustSize(size, precision) {
	if (isNaN(precision) || precision <= 0)
		precision = 6;
	if (size < KB)
		return round(size, precision) + ' B';
	else if (size < MB)
		return round(size / KB, precision) + ' KB';
	else if (size < GB)
		return round(size / MB, precision) + ' MB';
	else if (size < TB)
		return round(size / GB, precision) + ' GB';
	else
		return round(size / TB, precision) + ' TB';
}

